// 引入axios
import axios from "axios";
// import { config } from "vue/types/umd";

// 引入store仓库，以便取出tken
import store from "@/store";


// 引入组件message
import { Message } from "element-ui";

// 封装公共地址
const instance = axios.create({
    baseURL: 'http://sell.h5.itsource.cn:8087',  //公共地址
    timeout: 10000      //超时时间
})

// 封装请求拦截器
instance.interceptors.request.use(
    config => {
        // 1、获取token
        const token = store.getters.token
        // 将token挂载在config.headers的某个字段上(authorization)和后端商议的
        config.headers.authorization = token
        return config
    },
    err => {
        return Promise.reject(err)
    }
)

// 封装响应拦截器
instance.interceptors.response.use(
    response => {
        // 处理成功状态码
        let { msg, code } = response.data
        // 判断
        if (code === 0) {
            Message.success(msg)
        }
        if (code === 1) {
            Message.error(msg)
        }
        if (code === 5001) {
            Message.error(msg)
        }

        return response
    },
    err => {
        // 处理失败的状态码
        let { message, response } = err
        // 判断
        if (response) {
            switch (response.status) {
                case 401:
                    Message.error(message)
                    break;
                case 403:
                    Message.error(message)
                    break
                case 404:
                    Message.error(message)
                    break
                default:
                    break;
            }
        }

        return Promise.reject(err)
    }
)

// 导出封装好的axios
export default instance